package com.lianzhihui.romeex.ui.ecological;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.zxing.client.android.Intents;
import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.bean.EcologicalBean;
import com.lianzhihui.romeex.bean.SaveAddressInfo;
import com.lianzhihui.romeex.bean.WalletMainBean;
import com.lianzhihui.romeex.bean.user.WalletInfo;
import com.lianzhihui.romeex.config.AppConstants;
import com.lianzhihui.romeex.inter.DialogListener;
import com.lianzhihui.romeex.mvp.presenter.EcologicalPresnterImp;
import com.lianzhihui.romeex.mvp.view.EcologicalView;
import com.lianzhihui.romeex.ui.base.BaseActivity;
import com.lianzhihui.romeex.ui.me.AddressActivity;
import com.lianzhihui.romeex.ui.qrcode.ScanActivity;
import com.lianzhihui.romeex.utils.ImagesUtil;
import com.lianzhihui.romeex.utils.IntentUtils;
import com.lianzhihui.romeex.utils.LogUtil;
import com.lianzhihui.romeex.utils.NoDoubleClickUtils;
import com.lianzhihui.romeex.utils.NumberUtils;
import com.lianzhihui.romeex.utils.QrUtils.QRUtils;
import com.lianzhihui.romeex.utils.StatusBarUtil;
import com.lianzhihui.romeex.utils.StringTool;
import com.lianzhihui.romeex.utils.UserUtils;
import com.lianzhihui.romeex.widget.dialog.ZZFailDialog;
import com.lianzhihui.romeex.widget.dialog.ZZSucDialog;
import com.lianzhihui.romeex.widget.dialog.ZhuanzhangDialog;

import java.text.MessageFormat;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description: 积分转账
 * Author:
 * CreateDate: 2020/11/5 4:06 PM
 * UpdateUser:
 * UpdateDate:
 * UpdateRemark:
 * Version:
 */
public class IntegralTransferActivity extends BaseActivity implements EcologicalView {
    @BindView(R.id.include_top_tv_right)
    TextView includeTopTvRight;
    @BindView(R.id.include_top_lin_background)
    LinearLayout includeTopLinBackground;
    @BindView(R.id.shouqian_layout)
    CardView shouqian_layout;
    @BindView(R.id.zhuanzhang_layout)
    LinearLayout zhuanzhang_layout;
    @BindView(R.id.shoukuan)
    TextView shoukuan;
    @BindView(R.id.zhuanzhang)
    TextView zhuanzhang;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.tv_canuse)
    TextView tv_canuse;
    @BindView(R.id.tv_service)
    TextView tv_service;
    @BindView(R.id.tv_suoha)
    TextView tv_suoha;
    @BindView(R.id.tv_target)
    EditText tv_target;
    @BindView(R.id.et_sum)
    EditText et_sum;
    @BindView(R.id.iv_qrcode)
    ImageView iv_qrcode;
    @BindView(R.id.bt_submit)
    Button bt_submit;
    @BindView(R.id.rl_qr_image)
    RelativeLayout rl_qr_image;
    private WalletMainBean.CoinBean coin;
    WalletInfo walletInfo;
    double sum = 0D;
    private EcologicalPresnterImp ecologicalPresnterImp;
    private String minerIntegral = "0";
    private String transferFeeRate;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_integral_transfer_layout;
    }

    @Override
    protected void initView() {
        StatusBarUtil.setTransparent(this);
        StatusBarUtil.setStatusBarTextColor(this, false);
        includeTopLinBackground.setBackgroundColor(getResources().getColor(R.color.transparent));
        setTitle(getResources().getString(R.string.text_node_trans_collection));

        includeTopTvRight.setText(getString(R.string.text_trans_recode));
        includeTopTvRight.setTextColor(getResources().getColor(R.color.trade_text_333333_color));
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            coin = (WalletMainBean.CoinBean) extras.get("coin");
        }
        walletInfo = UserUtils.getCurrentUser();
        address.setText(null != walletInfo ? walletInfo.getRoAddress() : "");
        ecologicalPresnterImp = new EcologicalPresnterImp(this, this);
        et_sum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //限制输入小数位数(2位)
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 8) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 8 + 1);
                        et_sum.setText(s);
                        et_sum.setSelection(s.length());
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        madeQR();
    }


    @Override
    protected void initData() {
        ecologicalPresnterImp.requestMinnerMyBalance();
    }


    @OnClick({R.id.shoukuan, R.id.zhuanzhang, R.id.bt_submit, R.id.tv_suoha, R.id.address, R.id.iv_address_book, R.id.iv_scan, R.id.include_top_tv_right})
    public void OnClick(View v) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            switch (v.getId()) {
                case R.id.shoukuan:
                    setTitle(getResources().getString(R.string.text_node_trans_collection));

                    bt_submit.setText(getString(R.string.save_qrcode));
                    showshouqianLayout();
                    break;
                case R.id.bt_submit:
                    if (bt_submit.getText().toString().equals(getString(R.string.save_qrcode))) {
                        save();
                        return;
                    }
                    if (TextUtils.isEmpty(et_sum.getText().toString())) {
                        toast("请输入正确的数量");
                        return;
                    }
                    String v1 = NumberUtils.big8(et_sum.getText().toString());

                    if (Double.parseDouble(v1) <= 0) {
                        toast("请输入正确的数量");
                        return;
                    }
                    if (Double.parseDouble(v1) > Double.parseDouble(minerIntegral)) {
                        toast("转账金额超出可用余额");
                        return;
                    }
                    if (TextUtils.isEmpty(tv_target.getText().toString())) {
                        toast("请输入收款地址");
                        return;
                    }
                    String pat = "^[0-9]+(\\.[0-9]{1,8})?$";
                    boolean matches = Pattern.matches(pat, et_sum.getText().toString());
                    if ((et_sum.getText().toString().trim().isEmpty() || !matches) || Double.parseDouble(et_sum.getText().toString().trim()) <= 0) {
                        toast(getString(R.string.text_correct_money));
                        return;
                    }
                    ZhuanzhangDialog dialog = new ZhuanzhangDialog(this);
                    dialog.setSum(v1, "XUSD");
                    dialog.setTitle(getString(R.string.text_trans_sure));
                    dialog.setTitle_trans(getString(R.string.text_node_trans_out_count));
                    dialog.setListener(new DialogListener() {
                        @Override
                        public void onPassed() {
                            showLoading("");
                            long value = (long) (Double.parseDouble(v1) * 100000000L);
                            ecologicalPresnterImp.requestMinnerTransfer(tv_target.getText().toString(), String.valueOf(value));
                            dialog.dismiss();
                        }

                        @Override
                        public void onFail() {
                            toast("安全码错误");
                        }
                    });
                    dialog.show();

                    break;
                case R.id.tv_suoha:
                    double temp = Double.parseDouble(minerIntegral) * (1 - Double.parseDouble(transferFeeRate));
                    et_sum.setText(String.valueOf(temp));
                    break;
                case R.id.zhuanzhang:
                    setTitle(getResources().getString(R.string.text_node_trans));
                    bt_submit.setText(getString(R.string.text_confirm));
                    showTransLayout();
                    break;
                case R.id.include_top_tv_right:
                    IntentUtils.JumpTo(IntegralTransferRecordActivity.class);
                    break;
                case R.id.address:
                    copyString(address.getText().toString());
                    break;
                case R.id.iv_scan:
                    startActivityForResult(new Intent(this, ScanActivity.class), AppConstants.Intent.SCAN);
                    break;
                case R.id.iv_address_book:
                    Intent intent = new Intent(this, AddressActivity.class);
                    intent.putExtra("isSelect", 0);
                    startActivityForResult(intent, AppConstants.Intent.ADDRESS);
                    break;
                default:
                    break;
            }
        }
    }

    private void showTransLayout() {
        if (shouqian_layout.getVisibility() == View.VISIBLE) {
            shouqian_layout.setVisibility(View.GONE);
        }
        if (zhuanzhang_layout.getVisibility() == View.GONE) {
            zhuanzhang_layout.setVisibility(View.VISIBLE);
        }
        shoukuan.setBackgroundResource(R.drawable.tv_stoke_gray_left_9dp);
        zhuanzhang.setBackgroundResource(R.drawable.tv_solid_pruple_right_9dp);
        shoukuan.setTextColor(getResources().getColor(R.color.text_24254B_color));
        zhuanzhang.setTextColor(getResources().getColor(R.color.white));

    }

    private void showshouqianLayout() {
        if (zhuanzhang_layout.getVisibility() == View.VISIBLE) {
            zhuanzhang_layout.setVisibility(View.GONE);
        }
        if (shouqian_layout.getVisibility() == View.GONE) {
            shouqian_layout.setVisibility(View.VISIBLE);
        }
        shoukuan.setBackgroundResource(R.drawable.tv_solid_pruple_left_9dp);
        zhuanzhang.setBackgroundResource(R.drawable.tv_stoke_gray_right_9dp);
        shoukuan.setTextColor(getResources().getColor(R.color.white));
        zhuanzhang.setTextColor(getResources().getColor(R.color.text_24254B_color));
    }

    /**
     * 生成二维码
     */
    private void madeQR() {
        if (coin == null && TextUtils.isEmpty(coin.getCoinNameAlias())) {
            return;
        }
        String s1 = walletInfo == null ? "" : (TextUtils.isEmpty(walletInfo.getAddress()) ? "" : walletInfo.getAddress());
        String addrWithValue = QRUtils.type6 + s1;
        LogUtil.error("ramon", "addrWithValue: " + addrWithValue);
        ImagesUtil.createQrCodeImg(addrWithValue, iv_qrcode, 300);

    }


    @SuppressLint("SetTextI18n")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == AppConstants.Intent.ADDRESS) {
            //加载地址
            SaveAddressInfo.Address addressBean = (SaveAddressInfo.Address) data.getSerializableExtra("bean");
            tv_target.setText(addressBean.getAddress());
        }
        // 扫描二维码/条码回传
        //todo 二维码 导入私钥回调
        if (requestCode == AppConstants.Intent.SCAN) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra(Intents.Scan.RESULT);
                LogUtil.error("ramon", "result: " + content);
                if (TextUtils.isEmpty(content)) {
                    toast("无效二维码");
                    return;
                }

                switch (QRUtils.scanType(content)) {
                    case 6:
                        //转账
                        String scanResult = QRUtils.getContentString(content, 6);
                        tv_target.setText(StringTool.addHead(scanResult));
//                        tv_type.setText(coin.getCoinNameAlias());
                        break;
                    case 2:
                        //地址
                        String tagAddress = QRUtils.getContentString(content, 2);
                        tv_target.setText(StringTool.addHead(tagAddress));
                        break;
                    default:
                        break;
                }
            }
        }
    }

    @Override
    public void responseMinnerMyBalanceSuccess(EcologicalBean b) {
        if (b != null) {
            minerIntegral = b.getMinerIntegral();
            transferFeeRate = b.getTransferFeeRate();
            tv_service.setText(transferFeeRate);
            tv_canuse.setText(MessageFormat.format("{0} {1}", minerIntegral, getResources().getString(R.string.text_xusd)));
        }
    }

    @Override
    public void responseMinnerTransferSuccess() {
        dismissLoading();
        ecologicalPresnterImp.requestMinnerMyBalance();
//        finish();
        if (!this.isDestroyed()) {
            ZZSucDialog sucDialog = new ZZSucDialog(this);
            String v1 = NumberUtils.big8(et_sum.getText().toString());
            sucDialog.setSum(v1, getString(R.string.text_xusd));
            sucDialog.setListener(new DialogListener() {
                @Override
                public void onPassed() {
                    //跳转详情
                    IntentUtils.JumpTo(IntegralTransferRecordActivity.class);
                }

                @Override
                public void onFail() {

                }
            });
            sucDialog.show();
        }
        et_sum.setText("0");
//        toast(getString(R.string.text_trans_success));
    }

    @Override
    public void setFailure() {
        dismissLoading();
        if (!this.isDestroyed()) {
            ZZFailDialog failDialog = new ZZFailDialog(this);
            if (null != et_sum && TextUtils.isEmpty(et_sum.getText().toString())) {
                String v1 = NumberUtils.big8(et_sum.getText().toString());
                failDialog.setSum(v1, getString(R.string.text_xusd));
                failDialog.show();
            } else {
                failDialog.setSum(0, getString(R.string.text_xusd));
                failDialog.show();
            }
        }


    }

    private void save() {
        String[] PERMISSIONS = {
                "android.permission.READ_EXTERNAL_STORAGE",
                "android.permission.WRITE_EXTERNAL_STORAGE"};
        //检测是否有写的权限
        int permission = ContextCompat.checkSelfPermission(this,
                "android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有写的权限，去申请写的权限，会弹出对话框
            ActivityCompat.requestPermissions(this, PERMISSIONS, 1);
        } else {
            ImagesUtil.saveQrCode(this, rl_qr_image);
//            toast(getString(R.string.qrcode_save_successfully));
        }
    }

}
